
//
//  NSString+SS.m
//  SmartStore
//
//  Created by xieShou on 2020/4/13.
//  Copyright © 2020 xichuan. All rights reserved.
//

#import "NSString+SS.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

// 秘钥key  注：秘钥key size不超过16字节。
const NSString *AESKey = @"jtysosh234lesdhf0w3LHSFow9eru89@#$%^%$#)(*&^%$#@!HSFow9eru8wpoejfasl;fjasl;fsakflsakdfkjasdlfdasflmasd;/./.,?/s.fasf;asf]asd\f{}{}\[]sd[fp!@#$%^&*()_+?><MNBVCXZASDFGHJKL:POIUYTREWQ`~!1@2#4$4%5^6&7*8(9)0";



//#import <GZIP.h>
@implementation NSString (SS)
- (NSString *)URLEncodedString
{
  NSString *  result = [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    result = [result stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];

    return result;
}
- (NSString *)urlDecodeString {

    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,                                                 (__bridge CFStringRef)self,CFSTR(""),CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}
- (NSString *)encodeUrl {
        NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)self,NULL,CFSTR("!*'();:@&=+$,/?%#[]"),kCFStringEncodingUTF8));
    return result;

    
    
}
+(NSString *)URLEncodedString2:(NSString *)str{

    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)str,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return encodedString;
}
+ (NSString *)URLDecodedString2:(NSString *)str{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}


+ (NSDate *)dateWithCustomDateFormat:(NSString *)dateStr {
    NSDate  *currentDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
    NSString * _nowYear = [NSString stringWithFormat:@"%@",@([components year])];
    
    
    NSDateFormatter * dateF = [[NSDateFormatter alloc] init];
    dateF.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
    if ([dateStr containsString:@"T"]) {
        dateF.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
        return [dateF dateFromString:dateStr];
    }else{
        NSArray *tmpS1 = [dateStr componentsSeparatedByString:@"-"];
        NSArray *tmpS2 = [dateStr componentsSeparatedByString:@":"];
        NSArray *tmpS3 = [dateStr componentsSeparatedByString:@"/"];
        NSString *dateFormat = nil;
        NSString *time = nil;
        if (tmpS1.count == 2) {
            if ([[tmpS1 objectAtIndex:0] length] == 4) {
                dateFormat = @"yyyy-MM";
            }else{
                dateStr = [NSString stringWithFormat:@"%@-%@",_nowYear,dateStr];
                dateFormat = @"yyyy-MM-dd";
            }
        }else if(tmpS1.count == 3){
            dateFormat = @"yyyy-MM-dd";
        }else if (tmpS3.count == 2){
            if ([[tmpS3 objectAtIndex:0] length] == 4) {
                dateFormat = @"yyyy/MM";
            }else{
                dateStr = [NSString stringWithFormat:@"%@/%@",_nowYear,dateStr];
                dateFormat = @"yyyy/MM/dd";
            }
        }else if (tmpS3.count == 3){
            dateFormat = @"yyyy/MM/dd";
        }
        
        if ([tmpS2 count] == 2) {
            time = @"HH:mm";
        }else if(tmpS2.count == 3){
            time = @"HH:mm:ss";
        }
        
        NSString *totalFormat = nil;
        if (!kStringIsEmpty(dateFormat) && !kStringIsEmpty(time)) {
            totalFormat = [NSString stringWithFormat:@"%@ %@",dateFormat,time];
        }else if (!kStringIsEmpty(dateFormat)){
            totalFormat = dateFormat;
        }else if (!kStringIsEmpty(time)){
            totalFormat = time;
        }
        
        if (!kStringIsEmpty(totalFormat)) {
            dateF.dateFormat = totalFormat;
            return [dateF dateFromString:dateStr];
        }else{
            //无法解析成NSDate
            return nil;
        }
    }
}

- (NSString *)getUpdateStringWith:(NSDate *)date {
    if (!date || ![date isKindOfClass:[NSDate class]]) {
        return @"long long ago";
    } else {
        NSString *unit = nil;
        NSInteger number = 0;
        NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:date];
        if (interval > 365 * 24 * 60 * 60) {
            number = interval / (365 * 24 * 60 * 60);
            unit = @"年";
        } else if (interval > 30 * 24 * 60 * 60) {
            number = interval / (30 * 24 * 60 * 60);
            unit = @"月";
        } else if (interval > 24 * 60 * 60) {
            number = interval / (24 * 60 * 60);
            unit = @"天";
        } else if (interval > 60 * 60) {
            number = interval / (60 * 60);
            unit = @"小时";
        } else if (interval > 60) {
            number = interval / 60;
            unit = @"分钟";
        } else {
            return @"刚刚";
        }
        return [NSString stringWithFormat:@"%zi%@前",number,unit];
    }
}

+ (NSTimeInterval)getIntegerWithTime:(NSString *)times {
    NSDate *date = [NSString dateWithCustomDateFormat:times];
    return [date timeIntervalSince1970];
}

+ (NSString *)getCurrentTime:(NSString *)format {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:format];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
}
+ (NSString*)getCurrentFormatTimes{
    
    return [NSString getCurrentTime:@"YYYY-MM-dd HH:mm:ss"];
    
}
+(NSString *)getNowTimeTimestamp{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
//    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];

    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    return timeSp;
    
}
+(NSString *)getNowTimeSince{
    
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval a=[dat timeIntervalSince1970];
    
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    
    
    return timeString;
    
}
#pragma mark - 将某个时间戳转化成 时间

+(NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format{
    
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:format];
    
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
    
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    
    return confromTimespStr;
    
}
  
+(NSString *)getNowTimeTimeWithHaoMiao{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    
    return timeSp;
}
- (CGFloat)getStringHeightWithText:(NSString *)text font:(UIFont *)font viewWidth:(CGFloat)width {
    // 设置文字属性 要和label的一致
    NSDictionary *attrs = @{NSFontAttributeName :font};
    CGSize maxSize = CGSizeMake(width, MAXFLOAT);
    
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    
    // 计算文字占据的宽高
    CGSize size = [text boundingRectWithSize:maxSize options:options attributes:attrs context:nil].size;
    
    // 当你是把获得的高度来布局控件的View的高度的时候.size转化为ceilf(size.height)。
    return  ceilf(size.height);
}
+ (NSString *)convertFileSize:(long long)size {
    long kb = 1024;
    long mb = kb * 1024;
    long gb = mb * 1024;
    
    if (size >= gb) {
        return [NSString stringWithFormat:@"%.1f GB", (float) size / gb];
    } else if (size >= mb) {
        float f = (float) size / mb;
        if (f > 100) {
            return [NSString stringWithFormat:@"%.0f MB", f];
        }else{
            return [NSString stringWithFormat:@"%.1f MB", f];
        }
    } else if (size >= kb) {
        float f = (float) size / kb;
        if (f > 100) {
            return [NSString stringWithFormat:@"%.0f KB", f];
        }else{
            return [NSString stringWithFormat:@"%.1f KB", f];
        }
    } else
        return [NSString stringWithFormat:@"%lld B", size];
}

- (BOOL)isPhoneNumber {
    NSString *reg = @"^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(19[0-9]{1})|(17[0-9]{1})|(14[4-7]{1}))+\\d{8})$";
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];
    return [regextestcm evaluateWithObject:self];
}
- (BOOL)isTrueUrl {
    NSString *pattern = @"http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
    NSArray *regexArray = [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
    if (regexArray.count > 0) return YES; else return NO;
}
- (BOOL)checkPassWord{
    
    NSString *passWordRegex = @"^[\\x21-\\x7e]{8,20}$";
    
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    
    if ([passWordPredicate evaluateWithObject:self]) {
        
        NSInteger index = 0;
        
        
        passWordRegex = @".*[0-9]+.*";
        
        passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
        
        if ([passWordPredicate evaluateWithObject:self]) {
            
            index ++;
            
        }
        
        
        passWordRegex = @".*[a-z]+.*";
        
        passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
        
        if ([passWordPredicate evaluateWithObject: self]) {
            
            index ++;
            
        }
        
        
        passWordRegex = @".*[A-Z]+.*";
        
        passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
        
        if ([passWordPredicate evaluateWithObject:self]) {
            
            index ++;
            
        }
        
        
        passWordRegex = @".*[\\x21-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7B-\\x7F]+.*";
        
        passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
        
        if ([passWordPredicate evaluateWithObject:self]) {
            
            index ++;
            
        }
        if (index >= 3) {
            return YES;
            
        }
        
    }
    
    return NO;
    
}

// JSON字符串转化为字典
#pragma mark JSON字符串转化为字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableLeaves
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
- (NSString *)zipHtml {
    if (self == nil && self.length == 0) {
        return @"";
    }
//NSData *resultData = [[self encodeUrl] dataUsingEncoding:NSUTF8StringEncoding];
//NSData *htmlData = [resultData gzippedData];
//NSString *result = [htmlData base64EncodedStringWithOptions:0];
//return result;
    return self;
}
- (NSString *)unZipHtml {
    if (self == nil && self.length == 0) {
        return @"";
    }
//NSData *data= [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
//NSData *contentData =  [data gunzippedData];
//NSString *contentHtml = [[NSString alloc] initWithData:contentData encoding:NSUTF8StringEncoding];
//contentHtml = [contentHtml stringByReplacingOccurrencesOfString:@"+" withString:@" "];
//return contentHtml;
    return self;
}
/**
 *   去除空格   \r  \n
 */
- (NSString *)replaceWhitespaceAndNewlineCharacter{
//return [[[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] stringByReplacingOccurrencesOfString:@"\r" withString:@""] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    
//    return [[[[[[[[[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] stringByReplacingOccurrencesOfString:@"\r" withString:@""] stringByReplacingOccurrencesOfString:@"\n" withString:@""] stringByReplacingOccurrencesOfString:@"" withString:@" "] stringByReplacingOccurrencesOfString:@"”" withString:@"\\'"] stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"] stringByReplacingOccurrencesOfString:@"’" withString:@"\\'"]
//             stringByReplacingOccurrencesOfString:@"“" withString:@"\\'"]
//            stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"] ;
    
//    return [[[[[[[[[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] stringByReplacingOccurrencesOfString:@"\r" withString:@""] stringByReplacingOccurrencesOfString:@"\n" withString:@""] stringByReplacingOccurrencesOfString:@"" withString:@" "] stringByReplacingOccurrencesOfString:@"”" withString:@"\\'"] stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"] stringByReplacingOccurrencesOfString:@"’" withString:@"\\’"]
//             stringByReplacingOccurrencesOfString:@"“" withString:@"\\'"]
//            stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];
    
    return [[[[[[[[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] stringByReplacingOccurrencesOfString:@"\r" withString:@""] stringByReplacingOccurrencesOfString:@"\n" withString:@""] stringByReplacingOccurrencesOfString:@"”" withString:@"\\'"] stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"] stringByReplacingOccurrencesOfString:@"’" withString:@"\\’"]
             stringByReplacingOccurrencesOfString:@"“" withString:@"\\'"]
            stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];
    
}



/**
 *   获取是本周 还是更早
 */
+ (NSString *)getThisWeekOrEarlierStringWith:(NSDate *)date {
    
        NSTimeInterval tempInterval = [[NSDate date] timeIntervalSinceDate:date];
        
        NSTimeInterval betweenInterval = [[NSDate date] timeIntervalSinceDate:[NSDate date]];
    
        NSTimeInterval betweenInterval2 = betweenInterval-(7 * 24 * 60 * 60);

        
        if ((tempInterval >= betweenInterval2)&&(tempInterval <= betweenInterval2)) {
            return @"本周";
        }else {
            return @"更早...";
        }
    
}
/**
 *   把时间字符串转换成NSDate
 */
+ (NSDate *)timeFromeString:(NSString *)timeString{
    
    NSString* timeStr = timeString;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    
//    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
//    [formatter setTimeZone:timeZone];
    
    NSDate* tempdate = [formatter dateFromString:timeStr];
//    NSLog(@"🍎🍎🍎🍎🍎🍎🍎tempdate==%@\n\n",tempdate);//时间戳的值
    return tempdate;
}


//返回0说明该日期不是今天、昨天、前天
// 返回 1是今天  2是昨天  3是前天
/**
 *   计算  距离现在的时间
 */
+ (NSString *)getUTCFormateDate:(NSDate *)newsDate
{


    NSString *dateContent;
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    NSDate *today=[[NSDate alloc] init];
    NSDate *yearsterDay =  [[NSDate alloc] initWithTimeIntervalSinceNow:-secondsPerDay];
    NSDate *qianToday =  [[NSDate alloc] initWithTimeIntervalSinceNow:-2*secondsPerDay];
    //假设这是你要比较的date：NSDate *yourDate = ……
    //日历
    NSCalendar* calendar = [NSCalendar currentCalendar];
//    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:newsDate];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:yearsterDay];
    NSDateComponents* comp3 = [calendar components:unitFlags fromDate:qianToday];
    NSDateComponents* comp4 = [calendar components:unitFlags fromDate:today];
//    返回 1是今天  2是昨天  3是前天
    if ( comp1.year == comp2.year && comp1.month == comp2.month && comp1.day == comp2.day) {
//        dateContent = @"昨天";
        dateContent = @"2";
    }
    else if (comp1.year == comp3.year && comp1.month == comp3.month && comp1.day == comp3.day)
    {
//        dateContent = @"前天";
        dateContent = @"3";
    }
    else if (comp1.year == comp4.year && comp1.month == comp4.month && comp1.day == comp4.day)
    {
//        dateContent = @"今天";
        dateContent = @"1";
    }
    else
    {
        //返回0说明该日期不是今天、昨天、前天
        dateContent = @"0";
    }
    return dateContent;
}



/**
 *   1 代表今天或者昨天  2代表本周  3代表更早
 *   计算距离现在的具体时间段
 */
+ (NSString *)getUTCFormateDate2:(NSDate *)newsDate
{
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    
    //假设这是你要比较的date：NSDate *yourDate = ……
    //日历
    NSCalendar* calendar = [NSCalendar currentCalendar];
//    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
//    NSDate *today=[[NSDate alloc] init];
//    NSDateComponents* todayComp = [calendar components:unitFlags fromDate:today];
    
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:newsDate];
    
    BOOL isFind = NO;
    int findIndex = 0;
    for(int i=0;i<8;i++){
        NSDate *tempYearsterDay =  [[NSDate alloc] initWithTimeIntervalSinceNow:-i*secondsPerDay];
        NSDateComponents* tempComp2 = [calendar components:unitFlags fromDate:tempYearsterDay];
        if ( comp1.year == tempComp2.year &&
            comp1.month == tempComp2.month &&
            comp1.day == tempComp2.day)
        {
    //        dateContent = @"昨天";
//            dateContent = @"2";
            isFind = YES;
            findIndex = i;
            break;
        }
    }
    
    if(isFind){
        if(findIndex==0||findIndex==1){
            return @"1";// 1 代表今天或者昨天
        }else if(findIndex>1&&findIndex<=6){
            return @"2";// 代表本周
        }else{
            return @"3";// 更早
        }
    }else{
        return @"3";// 更早
    }
}

-(NSString *)convertFileSize:(long long)size {
    long kb = 1024;
    long mb = kb * 1024;
    long gb = mb * 1024;
    
    if (size >= gb) {
        return [NSString stringWithFormat:@"%.1f GB", (float) size / gb];
    } else if (size >= mb) {
        float f = (float) size / mb;
        if (f > 100) {
            return [NSString stringWithFormat:@"%.0f MB", f];
        }else{
            return [NSString stringWithFormat:@"%.1f MB", f];
        }
    } else if (size >= kb) {
        float f = (float) size / kb;
        if (f > 100) {
            return [NSString stringWithFormat:@"%.0f KB", f];
        }else{
            return [NSString stringWithFormat:@"%.1f KB", f];
        }
    } else
        return [NSString stringWithFormat:@"%lld B", size];
}

#pragma mark map转jsonstring
+ (NSString *)convertToJsonData:(NSDictionary *) dict {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                        options:NSJSONWritingSortedKeys
                                        error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    } else {
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

///字符串是否为空:  空YES  非空NO
+ (BOOL)cy_isEmpty:(NSString *)string
{
    BOOL empty = NO;
    if ([string isEqual:[NSNull null]]) {
        empty = YES;
    }
    
    if (![string isKindOfClass:[NSString class]]){
        empty = YES;
        return empty;
    }
    if (string.length <=0 ){
        empty = YES;
    }
    
    if ([string isEqualToString:@"null"] || [string isEqualToString:@"(null)"] || [string isEqualToString:@""]) {
        empty = YES;
    }
    
    if (string == nil) {
        empty = YES;
    }
    
    return empty;
}

///字符串转字典
+ (NSDictionary*)cy_stringConversionDictionary:(NSString*)str{
    if ([NSString cy_isEmpty:str]) {
        str = @"";
    }
    NSString * jsonString = str;
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if (error) {
        return [NSDictionary new];
      //解析出错
    }
    return dic;
}
/**
*  设置行间距、字间距和文本颜色
*
*  @param lineSpace 行间距
*  @param kern      字间距
*  @param colorText 设置颜色的文本
*
*  @return 富文本
*/
-(NSMutableAttributedString *)getAttributedStringWithLineSpace:(NSString *) text lineSpace:(CGFloat)lineSpace kern:(CGFloat)kern colorText:(NSString *) colorText{
    NSMutableParagraphStyle * paragraphStyle = [NSMutableParagraphStyle new];
    //调整行间距
    paragraphStyle.lineSpacing= lineSpace;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    paragraphStyle.lineSpacing = lineSpace; //设置行间距
    paragraphStyle.firstLineHeadIndent = 30.0;//设置第一行缩进
    NSDictionary*attriDict =@{NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:@(kern)};
    
    NSRange colorTextRange = [text rangeOfString:colorText];
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:text];
    //设置文本颜色
    [attributeStr addAttribute:NSForegroundColorAttributeName
                         value:UIColor.redColor
                         range:colorTextRange];
    [attributeStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15.0f] range:colorTextRange];
    [attributeStr addAttributes:attriDict range:NSMakeRange(0, [text length])];
    
    return attributeStr;
}
/**
*  设置行间距和字间距
*
*  @param lineSpace 行间距
*  @param kern      字间距
*
*  @return 富文本
*/
-(NSMutableAttributedString *)getAttributedStringWithLineSpace:(NSString *) text lineSpace:(CGFloat)lineSpace kern:(CGFloat)kern {
    NSMutableParagraphStyle * paragraphStyle = [NSMutableParagraphStyle new];
    //调整行间距
    paragraphStyle.lineSpacing= lineSpace;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    paragraphStyle.lineSpacing = lineSpace; //设置行间距
    paragraphStyle.firstLineHeadIndent = 30.0;//设置第一行缩进
    NSDictionary*attriDict =@{NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:@(kern)};
    NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:text attributes:attriDict];
    
    return attributedString;
}

/**
 *  富文本部分字体设置颜色
 *
 *  @param text 文本
 *  @param highlightText  设置颜色的文本
 *
 *  @return 富文本
 */
- (NSMutableAttributedString *)setupAttributeString:(NSString *)text highlightText:(NSString *)highlightText {
    NSRange hightlightTextRange = [text rangeOfString:highlightText];
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:text];
    if (hightlightTextRange.length > 0) {
        [attributeStr addAttribute:NSForegroundColorAttributeName
                             value:UIColor.redColor
                             range:hightlightTextRange];
        [attributeStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15.0f] range:hightlightTextRange];
        return attributeStr;
    }else {
        return [highlightText copy];
    }
}

///字符串是否为空:  空YES  非空NO
+ (BOOL)zyf_isEmpty:(NSString *)string
{
    BOOL empty = NO;
    if ([string isEqual:[NSNull null]]) {
        empty = YES;
    }
    
    if (![string isKindOfClass:[NSString class]]){
        empty = YES;
        return empty;
    }
    if (string.length <=0 ){
        empty = YES;
    }
    
    if ([string isEqualToString:@"null"] || [string isEqualToString:@"(null)"] || [string isEqualToString:@""]) {
        empty = YES;
    }
    
    if (string == nil) {
        empty = YES;
    }
    
    return empty;
}

///字符串转字典
+ (NSDictionary*)zyf_stringConversionDictionary:(NSString*)str{
    if ([NSString zyf_isEmpty:str]) {
        str = @"";
    }
    NSString * jsonString = str;
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if (error) {
        return [NSDictionary new];
      //解析出错
    }
    return dic;
}


+ (NSString *)flattenHTML:(NSString *)html trimWhiteSpace:(BOOL)trim{
    NSScanner *theScanner = [NSScanner scannerWithString:html];
    NSString *text = nil;
    
    while ([theScanner isAtEnd] == NO){
        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL];
        // find end of tag
        [theScanner scanUpToString:@">" intoString:&text];
        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
    }
    // trim off whitespace
    return trim ? [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]:html;
}


+ (NSDictionary *)convert2DictionaryWithJSONString:(NSString *)jsonString{
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err){
        NSLog(@"convert2DictionaryWithJSONString--err==%@\n",err);
        return nil;
    }
    return dic;
}


// 字节数组转
+ (NSString *)stringFromByte:(Byte *)byteBuffer length:(NSInteger)length {
    NSMutableString *hexString = [[NSMutableString alloc] init];
    for (int i = 0; i < length; i++) {
        [hexString appendString:[NSString stringWithFormat:@"%0.2hhx", byteBuffer[i]]];
    }
    return [hexString uppercaseString];
}
 
+ (NSData *)ByteDataFromString:(NSString *)targetStr {
    NSInteger len = [targetStr length] / 2;    // Target length
    unsigned char *buf = malloc(len);
    unsigned char *whole_byte = buf;
    char byte_chars[3] = {'\0','\0','\0'};
 
    int i;
    for (i=0; i < [targetStr length] / 2; i++) {
        byte_chars[0] = [targetStr characterAtIndex:i*2];
        byte_chars[1] = [targetStr characterAtIndex:i*2+1];
        *whole_byte = strtol(byte_chars, NULL, 16);
        whole_byte++;
    }
 
    NSData *data = [NSData dataWithBytes:buf length:len];
    free( buf );
    return data;
}

/**
 * AES加密
 */
+ (NSString *)aesEncrypt:(NSString *)sourceStr{
    if (!sourceStr) {
        return nil;
    }
    char keyPtr[kCCKeySizeAES256 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [AESKey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
     
    NSData *sourceData = [sourceStr dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [sourceData length];
    size_t buffersize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(buffersize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding | kCCOptionECBMode, keyPtr, kCCBlockSizeAES128, NULL, [sourceData bytes], dataLength, buffer, buffersize, &numBytesEncrypted);
     
    if (cryptStatus == kCCSuccess) {
        NSData *encryptData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        //对加密后的二进制数据进行base64转码
        return [encryptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    } else {
        free(buffer);
        return nil;
    }
}
/**
 * AES解密
 */
+ (NSString *)aesDecrypt:(NSString *)secretStr{
    if (!secretStr) {
        return nil;
    }
    //先对加密的字符串进行base64解码
    NSData *decodeData = [[NSData alloc] initWithBase64EncodedString:secretStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
     
    char keyPtr[kCCKeySizeAES256 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [AESKey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
     
    NSUInteger dataLength = [decodeData length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding | kCCOptionECBMode, keyPtr, kCCBlockSizeAES128, NULL, [decodeData bytes], dataLength, buffer, bufferSize, &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        return result;
    } else {
        free(buffer);
        return nil;
    }
}
- (NSString *)appendCachePath {
    NSString *dir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    return [dir stringByAppendingPathComponent:self.lastPathComponent];
}

#pragma mark iOS 图片链接含有中文图片无法显示问题解决办法
- (NSString *)stringHaveChinse{
    
    return  [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}


//把地址中有中文的编码成UTF8 字符
+ (NSString *)changeUrlStringHaveChineseCharToUTF8String:(NSString *)changeStr{
    
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)changeStr,NULL,NULL,kCFStringEncodingUTF8));
}


// 匹配包含中文：利用rangeOfString:option:直接查找
+ (BOOL)validateRangeContainsChinese:(NSString *)content{
    NSString *regEx = @".*[\u4e00-\u9fa5].*";
    NSRange range = [content rangeOfString:regEx options:NSRegularExpressionSearch];
    return range.length;
    
}

// 正则匹配是否包含中文
+ (BOOL)validateContainsChinese:(NSString *)content

{

// ^[\u4e00-\u9fa5] 以中文开头 的字符串

// [\u4e00-\u9fa5] 包含中文

    NSRegularExpression *regularexpression = [[NSRegularExpression alloc] initWithPattern:@"^[\u4e00-\u9fa5]" options:NSRegularExpressionCaseInsensitive error:nil];
    return ([regularexpression numberOfMatchesInString:content options:NSMatchingReportProgress range:NSMakeRange(0, content.length)] > 0);
    
}

@end



